package cz.muni.fi.pa165.sportclubmanager.client.modules.ageCategory;

import cz.muni.fi.pa165.sportclubmanager.service.agecategory.AgeCategoryDTO;
import cz.muni.fi.pa165.sportclubmanager.service.agecategory.AgeCategoryWebService;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.SwingWorker;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Greegus
 */
public class AgeCategoriesListPanel extends javax.swing.JPanel {

    private List<AgeCategoryDTO> ageCategories;

    /**
     * Creates new form ageCategoryListPanel
     */
    public AgeCategoriesListPanel() {
        initComponents();
        reloadAgeCategories();
        jProgressBar1.setVisible(false);

    }

    public void reloadAgeCategories() {
        ReloadAgeCategoriesWorker worker = new ReloadAgeCategoriesWorker();
        jProgressBar1.setVisible(true);
        jProgressBar1.setIndeterminate(true);
        refreshButton.setEnabled(false);
        worker.execute();
    }

    public class ReloadAgeCategoriesWorker extends SwingWorker<Integer, Integer> {

        @Override
        protected Integer doInBackground() throws Exception {
            DefaultTableModel tableModel = (DefaultTableModel) table.getModel();

            while (tableModel.getRowCount() > 0) {
                tableModel.removeRow(0);
            }

            try {
                ageCategories = new AgeCategoryWebService().getAgeCategoryServiceImplPort().findAll();

                for (AgeCategoryDTO ageCategory : ageCategories) {
                    tableModel.addRow(new Object[]{
                                ageCategory.getName(),
                                Integer.toString(ageCategory.getAgeFrom()) + " - " + Integer.toString(ageCategory.getAgeTo()),
                                ageCategory.getId()
                            });
                }

                repaint();
            } catch (Exception e) {
                JOptionPane.showMessageDialog(AgeCategoriesListPanel.this,
                        "Error loading age categories",
                        "Error",
                        JOptionPane.ERROR_MESSAGE);
                return 1;
            }
            return 0;
        }

        @Override
        protected void done() {
            jProgressBar1.setVisible(false);
            jProgressBar1.setIndeterminate(false);
            refreshButton.setEnabled(true);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        tableContextMenu = new javax.swing.JPopupMenu();
        editMenuItem = new javax.swing.JMenuItem();
        deleteMenuItem = new javax.swing.JMenuItem();
        jScrollPane1 = new javax.swing.JScrollPane();
        table = new javax.swing.JTable();
        newAgeCategoryButton = new javax.swing.JButton();
        refreshButton = new javax.swing.JButton();
        jProgressBar1 = new javax.swing.JProgressBar();

        editMenuItem.setText("Edit age category");
        editMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editMenuItemActionPerformed(evt);
            }
        });
        tableContextMenu.add(editMenuItem);

        deleteMenuItem.setText("Delete age category");
        deleteMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteMenuItemActionPerformed(evt);
            }
        });
        tableContextMenu.add(deleteMenuItem);

        table.setAutoCreateRowSorter(true);
        table.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Title", "Age boundaries"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        table.setFillsViewportHeight(true);
        table.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tableRowOnDoubleClick(evt);
            }
            public void mousePressed(java.awt.event.MouseEvent evt) {
                openContextMenu(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                openContextMenu(evt);
            }
        });
        jScrollPane1.setViewportView(table);

        newAgeCategoryButton.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        newAgeCategoryButton.setText("Add new age category");
        newAgeCategoryButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newAgeCategoryButtonActionPerformed(evt);
            }
        });

        refreshButton.setText("Refresh list");
        refreshButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                refreshButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 565, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(refreshButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(newAgeCategoryButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 239, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(newAgeCategoryButton)
                        .addComponent(refreshButton))
                    .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void newAgeCategoryButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newAgeCategoryButtonActionPerformed
        new AgeCategoryForm(this);
    }//GEN-LAST:event_newAgeCategoryButtonActionPerformed

    private void openContextMenu(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_openContextMenu
        int r = table.rowAtPoint(evt.getPoint());

        if (r >= 0 && r < table.getRowCount()) {
            table.setRowSelectionInterval(r, r);
        } else {
            table.clearSelection();
        }

        int rowindex = table.getSelectedRow();

        if (rowindex < 0) {
            return;
        }

        if (evt.isPopupTrigger() && evt.getComponent() instanceof JTable) {
            tableContextMenu.show(evt.getComponent(), evt.getX(), evt.getY());
        }
    }//GEN-LAST:event_openContextMenu

    private void editMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editMenuItemActionPerformed
        int rowindex = table.getSelectedRow();

        if (rowindex < 0) {
            return;
        }

        rowindex = table.convertRowIndexToModel(rowindex);

        new AgeCategoryForm(ageCategories.get(rowindex), this);
    }//GEN-LAST:event_editMenuItemActionPerformed

    private void tableRowOnDoubleClick(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tableRowOnDoubleClick
        if (evt.getClickCount() == 2 && !evt.isConsumed()) {
            evt.consume();

            int rowindex = table.getSelectedRow();

            if (rowindex < 0) {
                return;
            }

            rowindex = table.convertRowIndexToModel(rowindex);

            new AgeCategoryForm(ageCategories.get(rowindex), this);
        }
    }//GEN-LAST:event_tableRowOnDoubleClick

    private void refreshButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshButtonActionPerformed
        reloadAgeCategories();
    }//GEN-LAST:event_refreshButtonActionPerformed

    private void deleteMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteMenuItemActionPerformed
        int rowindex = table.getSelectedRow();

        if (rowindex < 0) {
            return;
        }

        rowindex = table.convertRowIndexToModel(rowindex);

        new DeleteAgeCategoryDialog(ageCategories.get(rowindex), this);
    }//GEN-LAST:event_deleteMenuItemActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem deleteMenuItem;
    private javax.swing.JMenuItem editMenuItem;
    private javax.swing.JProgressBar jProgressBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton newAgeCategoryButton;
    private javax.swing.JButton refreshButton;
    private javax.swing.JTable table;
    private javax.swing.JPopupMenu tableContextMenu;
    // End of variables declaration//GEN-END:variables
}
